<template>
  <div style="width: 100%">
    <el-container>
      <el-header>
        <el-menu
            background-color="whitesmoke"
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            :ellipsis="false"
            @select="handleSelect"
            router
        >
          <el-menu-item index="/" style="font-size: 20px;color:#978435">
            <el-icon size="50">
              <ForkSpoon/>
            </el-icon>
            篝火
          </el-menu-item>
          <div class="flex-grow"/>
          <div style="display: flex; align-items: center">
            <el-menu-item index="">首页</el-menu-item>
            <el-menu-item index="">沸点</el-menu-item>
            <el-menu-item index="">课程</el-menu-item>
            <el-menu-item index="">直播</el-menu-item>
            <el-menu-item index="">活动</el-menu-item>
            <el-menu-item index="">竞赛</el-menu-item>
            <el-menu-item index="">商城</el-menu-item>
            <el-menu-item>
              <el-input v-model="keyword" @keyup.enter="search()"
                        style="position: relative;top: 0" placeholder="请输入搜索内容">
                <template #append>
                  <el-button :icon="Search" @click="search()"/>
                </template>
              </el-input>
            </el-menu-item>
            <div v-if="user==null" style="margin-bottom: 24px">
              <el-button style="position: relative; top: 13px" color="#626aef"
                         @click="handleClick=true">
                创作者中心
              </el-button>
              <el-dropdown>
                <el-button style=" position: relative; top: 13px" color="#626aef">
                  <el-icon><arrow-down/></el-icon>
                </el-button>
                <template #dropdown>
                    <div style="width: 380px">
                      <el-row>
                        <el-col :sm="4" style="margin-right: 10px" @click="handleClick=true">
                          <el-icon size="50">
                            <Tickets/>
                          </el-icon>
                          <el-button type="primary">写文章</el-button>
                        </el-col>
                        <el-col :sm="4" style="margin-right: 10px" @click="handleClick=true">
                          <el-icon size="50">
                            <Opportunity/>
                          </el-icon>
                          <el-button type="primary">发沸点</el-button>
                        </el-col>
                        <el-col :sm="4" style="margin-right: 10px" @click="handleClick=true">
                          <el-icon size="50">
                            <Notebook/>
                          </el-icon>
                          <el-button type="primary">写笔记</el-button>
                        </el-col>
                        <el-col :sm="4" style="margin-right: 10px" @click="handleClick=true">
                          <el-icon size="50">
                            <Monitor/>
                          </el-icon>
                          <el-button type="primary">写代码</el-button>
                        </el-col>
                        <el-col :sm="4" style="margin-right: 10px" @click="handleClick=true">
                          <el-icon size="50">
                            <MessageBox/>
                          </el-icon>
                          <el-button type="primary">草稿箱</el-button>
                        </el-col>
                      </el-row>
                    </div>
                </template>
              </el-dropdown>
            </div>
            <div v-if="user!=null" style="margin-bottom: 24px">
              <el-button @click="creation()"
                         style="position: relative; top: 13px" color="#626aef">
                创作者中心
              </el-button>
              <el-dropdown>
                <el-button style=" position: relative; top: 13px" color="#626aef">
                  <el-icon><arrow-down/></el-icon>
                </el-button>
                <template #dropdown>
                    <div style="width: 380px">
                      <el-row>
                        <el-col :sm="4" style="margin-right: 10px" @click="write()">
                          <el-icon size="50">
                            <Tickets/>
                          </el-icon>
                          <el-button type="primary">写文章</el-button>
                        </el-col>
                        <el-col :sm="4" style="margin-right: 10px">
                          <el-icon size="50">
                            <Opportunity/>
                          </el-icon>
                          <el-button type="primary">发沸点</el-button>
                        </el-col>
                        <el-col :sm="4" style="margin-right: 10px">
                          <el-icon size="50">
                            <Notebook/>
                          </el-icon>
                          <el-button type="primary">写笔记</el-button>
                        </el-col>
                        <el-col :sm="4" style="margin-right: 10px">
                          <el-icon size="50">
                            <Monitor/>
                          </el-icon>
                          <el-button type="primary">写代码</el-button>
                        </el-col>
                        <el-col :sm="4" style="margin-right: 10px">
                          <el-icon size="50">
                            <MessageBox/>
                          </el-icon>
                          <el-button type="primary">草稿箱</el-button>
                        </el-col>
                      </el-row>
                    </div>
                </template>
              </el-dropdown>
            </div>
          </div>
          <el-menu-item v-if="user!=null" style="background-color: whitesmoke;border: none" index="/message">
            <el-dropdown placement="bottom-end">
              <el-icon style="margin-top: 11px;" size="30">
                <Bell/>
              </el-icon>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="commentInform()">评论
                  <span v-if="countNewInformOfComment>0"
                        style="width: 22px;border-radius: 50%;background-color: red;margin-left: 5px;
                                display: flex;align-items: center;justify-content: center;">
                    {{ countNewInformOfComment }}
                  </span>
                  </el-dropdown-item>
                  <el-dropdown-item @click="likecollectInform()">赞和收藏
                    <span v-if="countNewInformOfLikeAndCollection>0"
                         style="width: 22px;border-radius: 50%;background-color: red;margin-left: 5px;
                                display: flex;align-items: center;justify-content: center;">
                      {{countNewInformOfLikeAndCollection}}
                    </span>
                  </el-dropdown-item>
                  <el-dropdown-item @click="system()">系统通知</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-menu-item>
          <!-- Form -->
          <el-button v-if="user==null" @click="handleClick=true" style="margin-top: 15px;">注册|登录</el-button>
          <el-dialog style="width: 400px;position: relative;" v-model="handleClick" title="登录篝火项目畅享更多权益">
          <span style=" border-bottom: 1px solid #ccc; /* 将下划线颜色设置为灰色 */
                        display: inline-flex;
                        width: 100%; /* 下划线宽度 */"></span>
            <el-row>
              <el-col :span="24">
                <el-form>
                  <div class="mt-4" style="width: 300px;" v-if="visible">
                    <div style="font-size: 18px;margin: 10px 0 0 5px;color: #1D2129">手机验证码登录|注册</div>
                    <el-form-item :rules="rules">
                      <el-input
                          :rules="phoneRules"
                          style="width: 300px"
                          v-model="userInfoByPhone.phone"
                          placeholder="请输入手机号"
                          class="input-with-select"
                      >
                        <template #prepend>
                          <el-select v-model="select" placeholder="+86中国大陆" style="width: 100px"
                                     default-first-option="true">
                            <el-option label="+86中国大陆" value="beijing"/>
                            <el-option label="+856中国香港" value="xianggang"/>
                            <el-option label="+853中国澳门" value="aomen"/>
                            <el-option label="+852中国台湾" value="taiwan"/>
                          </el-select>
                        </template>
                      </el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-input v-model="userInfoByPhone.captcha" placeholder="请输入验证码">
                        <template #append style="width: 50px">
                          <button ref="sendBtn" @click="opsForCaptcha()" :disabled="disabled || countdown > 0"
                                  style="border:none">
                            {{ countdown > 0 ? `重新获取 (${countdown})` : '获取验证码' }}
                          </button>
                        </template>
                      </el-input>
                    </el-form-item>
                    <el-button type="primary" style="width: 50px;float: left" @click="reg()">注册</el-button>
                    <el-button type="primary" style="width: 50px;float: left" @click="loginByPhone()">登录</el-button>
                    <el-button text @click="visible=false" style="float: right">密码登录</el-button>
                  </div>
                  <div style="width: 300px;" v-else>
                    <div style="font-size: 18px;margin: 10px 0 0 5px;color: #1D2129">密码登录|注册</div>
                    <el-form-item>
                      <el-input
                          style="width: 300px"
                          v-model="userInfoByUsername.username"
                          placeholder="请输入用户名"
                          class="input-with-select"
                      />
                    </el-form-item>
                    <el-form-item>
                      <el-input v-model="userInfoByUsername.password" type="password" placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-row>
                        <el-col :span="18">
                          <el-input v-model="userInfoByUsername.code" placeholder="请输入验证码"></el-input>
                        </el-col>
                        <el-col :span="6" v-if="button" @click="button=false">
                          <el-button type="primary" @click="getCode()">获取验证码</el-button>
                        </el-col>
                        <el-col :span="6" v-else>
                          <el-tooltip content="点击验证码刷新" placement="bottom"
                                      effect="light" show-after="500">
                            <img :src="codeImg" @click="refresh()" style="margin-left: 10px">
                          </el-tooltip>
                        </el-col>
                      </el-row>
                    </el-form-item>
                    <el-button type="primary" style="width: 100px;float: left" @click="loginByUsername()">登录</el-button>
                    <el-button text @click="visible=true" style="float: right">手机验证码注册|登录</el-button>
                  </div>
                </el-form>
              </el-col>
              <!--      -->
              <!--      <template #footer>-->
              <!--      <span class="dialog-footer">-->
              <!--        <el-button type="primary" @click="dialogFormVisible = false">-->
              <!--          Confirm-->
              <!--        </el-button>-->
              <!--      </span>-->
              <!--      </template>-->
            </el-row>
            <br>
            <p style="font-size: 16px; margin: 0 auto">注册登录即表示同意 用户协议 和 隐私政策</p>
          </el-dialog>
          <el-popover v-if="user!=null"
                      placement="bottom"
                      title="欢迎来到篝火聚集地"
                      :width="200" trigger="hover"
          >
            <template #reference>
              <div style="margin-top: 10px">
                <el-avatar :src="user.avatar"></el-avatar>
              </div>
            </template>
            <div style="text-align: center">
              <el-button size="small" type="info" @click="router.push('/manage')">修改资料</el-button>
              <br>
              <el-button size="small" type="info" @click="router.push('/personal')">我的主页</el-button>
              <br>
              <el-button size="small" type="warning" @click="logout()">退出登录</el-button>
              <el-button v-if="user.isAdmin==1"
                         size="small" type="danger" @click="router.push('/admin')">后台管理页面
              </el-button>
            </div>
          </el-popover>
        </el-menu>
      </el-header>
      <el-main>
        <router-view/>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>

import {onMounted, reactive, ref, watch} from 'vue'
import {Search} from '@element-plus/icons-vue'
import axios from "axios";
import router from "@/router";
import {ElMessage} from "element-plus";
import qs from "qs";
import tokenAxios from "@/http/request/TokenAxios";

const handleClick = ref(false)
const visible = ref(true)
const button = ref(true)
const select = ref('')
const countdown = ref(0);
const sendBtn = ref(null);
const disabled = ref(false);

const userInfoByPhone = ref({phone: "", captcha: ""})
const userInfoByUsername = ref({username: "", password: "", code: "", base64String: ""})
const rules = {
  phone: [
    {required: true, message: "手机号不能为空", trigger: "blur"},
    {pattern: /^\d{11}$/, message: "手机号必须是11位数字", trigger: "blur"},
  ],
};
const phoneRules = ref(rules.phone);


const user = ref(getUser());

const keyword = ref("")
function generateSearchUrl() {
  return BASE_URL+`:8080/search?q=${encodeURIComponent(keyword.value)}`;
}
//搜索
const search = ()=>{
  const searchUrl = generateSearchUrl();
  window.open(searchUrl, '_blank');
}

const logout = () => {
  if (confirm("你确定退出登录")) {
    tokenAxios.post(BASE_URL + ':49081/users/logout').then((response) => {
      console.log(response)
      if (response.state === 20000) {
        localStorage.removeItem('user');
        user.value = null;
        router.push('/');
        ElMessage.success("退出成功!");
      }
    })
  }
}

const startCountdown = () => {
  disabled.value = true;
  countdown.value = localStorage.getItem("countdown") || 60;

  const intervalObj = setInterval(() => {
    countdown.value--;
    if (countdown.value === 0) {
      disabled.value = false;
      clearInterval(intervalObj);
    }
  }, 100);
};
//发送手机验证码
const opsForCaptcha = () => {
  disabled.value = true;
  countdown.value = 5;
  let data = qs.stringify({phone: userInfoByPhone.value.phone});
  axios.post(BASE_URL + ':49081/users/captcha/phone', data).then((response) => {
    if (response.data.state === 20000) {
      ElMessage.success('操作成功')
    } else {
      ElMessage.error(response.data.message)
    }
  })
  const intervalObj = setInterval(() => {
    countdown.value--;
    if (countdown.value === 0) {
      disabled.value = false;
      clearInterval(intervalObj);
    }
  }, 100);
  // startCountdown();
};
watch(countdown, (newValue) => {
  if (newValue > 0 && sendBtn.value) {
    sendBtn.value.innerText = `重新获取 (${newValue})`;
  } else if (sendBtn.value) {
    sendBtn.value.innerText = "获取验证码";
  }
  // 将禁用时间保存到本地存储
  localStorage.setItem("countdown", String(newValue));
});

const codeImg = ref();

const getCode = () => {
  axios.get(BASE_URL + ':49081/users/captcha/code').then((response) => {
    console.log(response)
    if (response.data.state === 20000) {
      ElMessage.success('操作成功');
      codeImg.value = response.data.data;
      console.log(codeImg.value);
      userInfoByUsername.value.base64String = codeImg.value;
    } else {
      ElMessage.error(response.data.message)
    }
  })
}
//刷新图形验证码
const refresh = () => {
  getCode();
}

//注册
const reg = () => {
  let data = qs.stringify(userInfoByPhone.value);
  regAndLogin(BASE_URL + ':49280/users/register', data, 0);
}
//手机号登录
const loginByPhone = () => {
  let data = qs.stringify(userInfoByPhone.value);
  regAndLogin(BASE_URL + ':49081/users/login/phone', data);
}
//用户名登录
const loginByUsername = () => {
  let data = qs.stringify(userInfoByUsername.value);
  regAndLogin(BASE_URL + ':49081/users/login', data);
}
//type=0是注册
const regAndLogin = (url, data, type) => {
  axios.post(url, data).then((response) => {
    if (response.data.state === 20000) {
      //把注册成功的用户信息保存到localStorage里面
      if(type!=0){
      localStorage.user = JSON.stringify(response.data.data);
      }
      ElMessage.success(type === 0 ? "注册成功!" : "登录成功!");
      location.href = '/';  //返回首页 并刷新页面
    } else {
      ElMessage.error(response.data.message);
    }
  })
}

const creation = () => {
  router.push('/creation');
}
const write = () => {
  router.push('/text');
}
const commentInform = () => {
  router.push('/message/comment')
}
const likecollectInform = () => {
  router.push('/message/likecollect')
}

const countNewInformOfComment = ref();
const countNewInformOfLikeAndCollection = ref();

const countNewInforms = (type) => {
  tokenAxios.get(BASE_URL + ':49282/inform/' + type + '/newInform-count').then((response) => {
    if (response.state===20000){
      switch (type) {
        case 1: countNewInformOfComment.value=response.data;break;
        case 2: countNewInformOfLikeAndCollection.value=response.data;break;
      }
    }
  })
}

onMounted(() => {
  sendBtn.value = document.querySelector("[ref='sendBtn']");
  // 在页面加载时重新启动倒计时
  if (localStorage.getItem("countdown") > 0) {
    startCountdown();
  }
  if (getUser() != null) {
    countNewInforms(1);
    countNewInforms(2);
  }
});


</script>

<style scoped>
.flex-grow {
  flex-grow: 2;
}

.input-with-select {
  margin-top: 10px;
}
</style>

